package system_smtp_service

import (
	"os"
	"strings"
	"time"

	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/service/system_smtp_service/provider"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/util/pointer"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
)

func (cls *Smtp) SendTimeTo(ctx context.Context, log *model.SystemSmtpLog, attachments []*os.File) errors.Error {
	if nil == log {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_TP.S_TP.STT_TO.120830 log is nil")

		return errors.ErrorServerInternalError("ISS_TP.S_TP.STT_TO.120836", "异常的传入参数")
	}

	if model.SystemSmtpLogSendTypeTime != *log.SendType {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_TP.S_TP.STT_TO.181000 异常的发送类型，传入的发送日志发送类型为 %d", *log.SendType)

		return errors.ErrorServerInternalError("ISS_TP.S_TP.STT_TO.201006", "邮件日志发送类型不正确")
	}

	if model.SystemSmtpLogStatusPending != *log.Status {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_TP.S_TP.STT_TO.241106 异常的日志状态，传入的日志状态为 %d", *log.Status)

		return errors.ErrorServerInternalError("ISS_TP.S_TP.STT_TO.261113", "邮件日志状态不正确")
	}

	log.Status = pointer.New(model.SystemSmtpLogStatusSending)

	if err := cls.smtpLog.SaveSystemSmtpLog(ctx, log); nil != err {
		return err.Relation(errors.ErrorServerInternalError("ISS_TP.S_TP.STT_TO.331340", "更新邮件日志状态失败"))
	}

	p, err := cls.GetProvider()
	if nil != err {
		return err.Relation(errors.ErrorServerInternalError("ISS_TP.S_TP.STT_TO.381417", "获取邮件服务提供商失败"))
	}

	var cc = make([]string, 0)
	if nil != log.Cc && "" != *log.Cc {
		cc = strings.Split(*log.Cc, ",")
	}

	var bcc = make([]string, 0)
	if nil != log.Bcc && "" != *log.Bcc {
		bcc = strings.Split(*log.Bcc, ",")
	}

	var ats = make([]provider.Attachment, 0)
	for _, attachment := range attachments {
		ats = append(ats, provider.Attachment{
			Filename: attachment.Name(),
			Reader:   attachment,
		})
	}

	if err := p.Send(ctx, *log.From, strings.Split(*log.To, ","), cc, bcc, *log.Subject, *log.BodyType, *log.Body, ats); nil != err {
		log.Status = pointer.New(model.SystemSmtpLogStatusFailed)
		log.FailedReason = pointer.New(err.Error())

		if err := cls.smtpLog.SaveSystemSmtpLog(ctx, log); nil != err {
			logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_TP.S_TP.STT_TO.682050 更新邮件日志失败，错误信息为 %q", err.Error())
		}

		return err.Relation(errors.ErrorServerInternalError("ISS_TP.S_TP.STT_TO.642021", "发送邮件失败"))
	}

	log.From = pointer.New(p.GetFrom())
	log.Provider = pointer.New(p.GetName())
	log.Status = pointer.New(model.SystemSmtpLogStatusSuccess)
	log.CompleteTime = pointer.New(time.Now().Unix())

	if err := cls.smtpLog.SaveSystemSmtpLog(ctx, log); nil != err {
		return err.Relation(errors.ErrorServerInternalError("ISS_TP.S_TP.STT_TO.792106", "更新邮件日志失败"))
	}

	return nil
}
